// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"html/template"
	"log"
	"net/http"
	"chat/ws"
	"os"
	"bytes"
	"path/filepath"
	"fmt"
	"strings"
)

var (

	addr          = flag.String("addr", "192.168.16.123:8080", "http service address")
	redisServer   = flag.String("redisServer", "127.0.0.1:6379", "redis addr")
	redisPassword = flag.String("redisPassword", "", "redis password")
)

func getTemplatesPath() *bytes.Buffer{
	root_path,_ := os.Getwd()
	path := bytes.Buffer{}
	path.WriteString(root_path)
	local_path:=filepath.FromSlash("/../templates/")
	path.WriteString(local_path)
	return &path
}


func serveHome(w http.ResponseWriter, r *http.Request) {
	log.Println(r.URL)

	if r.URL.Path != "/" {
		http.Error(w, "Not found", 404)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	templatefile :=getTemplatesPath()
	templatefile.WriteString("home.html")
	homeTemplate:=template.Must(template.ParseFiles(templatefile.String()))
	homeTemplate.Execute(w, r.Host)
}

func room(w http.ResponseWriter, r *http.Request){
	log.Println(r.URL)
	if r.URL.Path != "/room" {
		http.Error(w, "Not found", 404)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	switch r.Method {
	case  "GET": {
		templatefile :=getTemplatesPath()
		templatefile.WriteString("room.html")
		client := ws.NewClient(*redisServer,*redisPassword)
		client.Run("SET","room","dsd,d")
		rest:=client.Run("GET","room")
		fmt.Printf("%s",rest)
		strings.Split(rest.(string),",")
		homeTemplate:=template.Must(template.ParseFiles(templatefile.String()))
		homeTemplate.Execute(w, "")
		defer client.Close()
	}
	case "POST":{

	}
	}


}

func main() {
	flag.Parse()
	hub := ws.NewHub()
	go hub.Run()
	fs := http.FileServer(http.Dir("../static/"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.HandleFunc("/", serveHome)
	http.HandleFunc("/room", room)
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		ws.ServeWs(hub, w, r)
	})
	fmt.Printf(" server on %s", *addr)
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}w
